<template>
  <el-dialog
    v-if="visible"
    :model-value="visible"
    :title="isEdit ? '编辑工会' : '新增工会'"
    width="600px"
    :before-close="handleClose"
    @update:model-value="(val) => emit('update:visible', val)"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="union-form"
    >
      <el-form-item label="工会编号" prop="guildNo">
        <el-input
          v-model="formData.guildNo"
          placeholder="请输入工会编号"
          :disabled="isEdit"
        />
      </el-form-item>

      <el-form-item label="用户编号" prop="userNo">
        <el-input
          v-model="formData.userNo"
          placeholder="请输入用户编号"
          :disabled="isEdit"
        />
      </el-form-item>

      <el-form-item label="工会名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入工会名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="工会头像" prop="avatar">
        <el-input
          disabled
          v-model="formData.avatar"
          placeholder="请输入头像URL"
        />
        <div class="avatar-preview" v-if="formData.avatar">
          <Upload
            class="avatar-upload"
            :showFileList="false"
            :ossDir="OSS_DIR.RESOURCE_HEAD"
            accept=".jpg,.jpeg,.png"
            buttonText="上传头像"
            @upload-success="handleUploadSuccess"
          />
          <el-image
            :src="formData.avatar"
            fit="cover"
            style="width: 60px; height: 60px; border-radius: 8px"
            :preview-src-list="[formData.avatar]"
          />
        </div>
      </el-form-item>

      <el-form-item label="公告/宣言" prop="announcement">
        <el-input
          v-model="formData.announcement"
          type="textarea"
          :rows="4"
          placeholder="请输入公告或宣言内容"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { unionUpdateApi, type UnionUpdateReq } from "@/api/union";
import Upload from "@/components/upload/OssUpload.vue";
import { OSS_DIR } from "@/api/oss";

interface Props {
  visible: boolean;
  isEdit: boolean;
  unionData?: any;
}

interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();
const loading = ref(false);

const formData = reactive({
  guildNo: "",
  userNo: "",
  name: "",
  avatar: "",
  announcement: "",
});

const formRules: FormRules = {
  guildNo: [{ required: true, message: "请输入工会编号", trigger: "blur" }],
  userNo: [{ required: true, message: "请输入用户编号", trigger: "blur" }],
  name: [
    { required: true, message: "请输入工会名称", trigger: "blur" },
    { min: 1, max: 50, message: "工会名称长度在1-50个字符", trigger: "blur" },
  ],
  announcement: [
    { max: 500, message: "公告内容不能超过500个字符", trigger: "blur" },
  ],
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.isEdit && props.unionData) {
      // 编辑模式，填充表单数据
      Object.assign(formData, {
        guildNo: props.unionData.guildNo || "",
        userNo: props.unionData.ownerUserNo || "",
        name: props.unionData.name || "",
        avatar: props.unionData.avatar || "",
        announcement: props.unionData.announcement || "",
      });
    } else if (newVal && !props.isEdit) {
      // 新增模式，清空表单
      Object.assign(formData, {
        guildNo: "",
        userNo: "",
        name: "",
        avatar: "",
        announcement: "",
      });
    }
  }
);

// 上传成功，保存到表单变量
const handleUploadSuccess = (file: any) => {
  formData.avatar = file;
};

const handleClose = () => {
  emit("update:visible", false);
  formRef.value?.clearValidate();
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;

    // 构建提交数据
    const submitData = {
      guildNo: formData.guildNo,
      userNo: formData.userNo,
      name: formData.name,
      avatar: formData.avatar,
      announcement: formData.announcement,
    };

    await unionUpdateApi(submitData);

    ElMessage.success("操作成功");
    emit("success");
    handleClose();
  } catch (error: any) {
    ElMessage.error(error.message || "操作失败");
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.union-form {
  padding: 20px 0;
}

.avatar-preview {
  margin-top: 8px;
}

.avatar-upload{
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-input__inner) {
  font-size: 16px;
}

:deep(.el-textarea__inner) {
  font-size: 16px;
}
</style>
